package cn.luyou.admin.service.impl;

import cn.luyou.admin.entity.ExamRecordDetail;
import cn.luyou.admin.entity.Question;
import cn.luyou.admin.mapper.ExamRecordDetailMapper;
import cn.luyou.admin.service.ExamRecordDetailService;
import cn.luyou.admin.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ExamRecordDetailServiceImpl extends ServiceImpl<ExamRecordDetailMapper, ExamRecordDetail> implements ExamRecordDetailService {

    @Autowired
    private QuestionService questionService;

    @Override
    @Transactional
    public void saveRecordDetails(Long recordId, Map<Long, String> answers, Map<Long, Integer> questionScores) {
        // 删除原有记录
        deleteRecordDetails(recordId);
        
        // 获取所有题目信息
        List<Question> questions = questionService.listByIds(answers.keySet());
        
        // 保存新的记录
        List<ExamRecordDetail> details = new ArrayList<>();
        for (Question question : questions) {
            String userAnswer = answers.get(question.getId());
            boolean isCorrect = question.getCorrectAnswer().equals(userAnswer);
            Integer score = isCorrect ? questionScores.get(question.getId()) : 0;
            
            ExamRecordDetail detail = new ExamRecordDetail()
                    .setRecordId(recordId)
                    .setQuestionId(question.getId())
                    .setAnswer(userAnswer)
                    .setScore(score)
                    .setIsCorrect(isCorrect);
            details.add(detail);
        }
        
        this.saveBatch(details);
    }

    @Override
    public List<ExamRecordDetail> getRecordDetails(Long recordId) {
        return this.list(new LambdaQueryWrapper<ExamRecordDetail>()
                .eq(ExamRecordDetail::getRecordId, recordId));
    }

    @Override
    public List<ExamRecordDetail> getWrongQuestions(Long userId) {
        return baseMapper.selectWrongQuestions(userId);
    }

    @Override
    @Transactional
    public void deleteRecordDetails(Long recordId) {
        this.remove(new LambdaQueryWrapper<ExamRecordDetail>()
                .eq(ExamRecordDetail::getRecordId, recordId));
    }
} 